// pages/needHelp/wait/wait.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"

const app = getApp()
// 声音播放管理器
const audioPlayer = wx.createInnerAudioContext();

Page({

  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.setData({
      playing: false
    })
    this.id = options.id
    this.content = API.FILE_DOWNLOAD + "?fileName=" + options.content + "&sessionId=" + app.globalData.sessionId + "&openId=" + app.globalData.openId + "&fileProp=" + API.fILE_PROP_APPOINTMENT

    // 自然播放结束处理事件
    audioPlayer.onEnded(() => {
      console.log("自然播放结束")

      // 只处理预约音频播放结束
      if (this.data.playing) {
        this.setData({
          playing: false
        })
      }
      if (this.returnToIndex) {
        wx.navigateBack({
          delta: 1
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.returnToIndex = false
  },

  playAudio: function() {
    // 判断是播放还是暂停
    if (this.data.playing) {
      // 暂停
      audioPlayer.stop()
      this.setData({
        playing: false
      })
    } else {
      audioPlayer.src = this.content
      audioPlayer.play()
      this.setData({
        playing: true
      })
    }
  },

  cancel: function() {
    var that = this
    audioPlayer.stop()
    wx.showModal({
      title: '提示',
      content: '您确定要取消此次预约吗？',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          requestUtil.post(API.CANCEL_APPOINTMENT, {
            appointmentId: that.id
          }).then(res => {
            console.log(res)
            that.returnToIndex = true
            // TODO 语音提示 取消预约成功，自动为您跳转首页 
            app.textToSpeech('取消预约成功，将为您跳转首页').then((res) => {
              audioPlayer.src = res
              audioPlayer.play()
            })
          }).catch(err => {
            console.log(err)
            // TODO 语音提示 取消预约失败，请重试
            app.textToSpeech('取消预约失败，请稍后重试').then((res) => {
              audioPlayer.src = res
              audioPlayer.play()
            })
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    audioPlayer.stop()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    // audioPlayer.destroy()
  },
})